'use strict';

const BaseController = require('./base.js');
class LoginController extends BaseController {
  async index() {
    await this.ctx.render("admin/login")
  }
  async doLogin(){
    console.log(this.ctx.request.body);
    //1、获取表单穿过来的数据 判断验证码是否正确
    //2、判断用户名密码是否合法
    //3、执行登录

    let username=this.ctx.request.body.username;
    let password=this.ctx.service.tools.md5(this.ctx.request.body.password);
    let verify=this.ctx.request.body.verify;
    
    if(verify==this.ctx.session.code){
      let userinfo=await this.ctx.model.Admin.findAll({
        where: {
          username: username,
          password:password
        }
      });
      console.log(userinfo);
      if(userinfo.length>0){
        this.ctx.session.userinfo=userinfo[0];        
        await this.success("登录成功",`/${this.config.adminPath}`);
      }else{       
        await this.error("用户名或者密码错误",`/${this.config.adminPath}/login`);
      }
    }else{      
      await this.error("验证码错误",`/${this.config.adminPath}/login`);
    }

  }
  async loginOut() {
    this.ctx.session.userinfo=null;
    await this.success("退出登录成功",`/${this.config.adminPath}/login`);
  }
  async captcha() {    
    let captcha = await this.service.tools.getCaptcha();
    console.log(captcha.text);
    this.ctx.session.code=captcha.text;
    this.ctx.response.type = 'image/svg+xml'; /*指定返回的类型*/ 
    this.ctx.body = captcha.data; /*给页面返回一张图片*/

  }
}

module.exports = LoginController;
